package vn.com.shoppie.activity;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import vn.com.shoppie.network.WiModelManager;
import vn.com.shoppie.object.BrandAdapter;
import vn.com.shoppie.sobject.Campaign;
import vn.com.shoppie.sobject.ShoppieObject;
import vn.com.shoppie.util.SConfig;
import vn.com.shoppie.util.SUtilXml;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BrandActivity extends Activity {
	public static final String MERCH_ID = "merchId";
	public static final String CAMPAIGN = "campaign";
	public static final String STORE = "store";

	private ArrayList<ShoppieObject> lstProduct;
	private ArrayList<ShoppieObject> lstGift;

	private String merchId = "";
	ShoppieObject data = null;

	int typeProduct = 0;
	int typeGift = 1;

	int typeSelected = typeProduct;
	BrandAdapter lstProductAdapter;
	BrandAdapter lstGiftAdapter;

	Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_brand);
		mHandler = new Handler();

		Intent brandIntent = this.getIntent();

		if (brandIntent.hasExtra(MERCH_ID)) {
			merchId = brandIntent.getStringExtra(MERCH_ID);
			if (merchId.equals(null) || merchId.equals("")) {
				showToast("Can not found brand.");
				this.finish();
			} else {
				// showToast(merchId);
			}
		}
		if (brandIntent.hasExtra(STORE)) {

		} else if (brandIntent.hasExtra(CAMPAIGN)) {

			final Campaign campaign = (Campaign) brandIntent
					.getSerializableExtra(CAMPAIGN);
			this.data = campaign;
			((TextView) findViewById(R.id.tv_title)).setText(campaign.name);
			((Button) findViewById(R.id.btn_heart)).setText(campaign.merchId);
			new AsyncTask<String, Integer, Boolean>() {
				@Override
				protected Boolean doInBackground(String... arg0) {
					if (campaign.getBitmap(getApplicationContext(), campaign.linkImage) == null) {
						String link = campaign.linkImage;
						link = link.replaceAll(" ", "%20");
						campaign.getBitmap(getApplicationContext(), campaign.linkImage);
					}
					return true;
				}
			}.execute("");
			// if(campaign.getBitmap(getApplicationContext(),
			// campaign.linkImage)==null){
			//
			// new Thread(){
			// public void run() {
			// String link = campaign.linkImage;
			// link=link.replaceAll(" ", "%20");
			// campaign.getBitmap(getApplicationContext(), campaign.linkImage);
			// };
			// }.start();
			// }
			new AsyncTask<String, Integer, Bitmap>(){

				@Override
				protected Bitmap doInBackground(String... arg0) {
					return campaign.getBitmap(getApplicationContext(), campaign.linkImage);
				}
				@Override
				protected void onPostExecute(Bitmap result) {
					if(result!=null){
						((ImageView) findViewById(R.id.iv_avatar)).setImageBitmap(result);
					}
				}
			}.execute("");
			
		}

		// PRODUCT
		lstProduct = new ArrayList<ShoppieObject>();
		lstProductAdapter = new BrandAdapter(this, lstProduct);
		new AsyncTask<String, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(String... arg0) {
				lstProduct = loadData(SConfig.URL_BRAND_PRODUCTS);
				return true;
			}

			protected void onPostExecute(Boolean result) {
				refreshUI();
			};
		}.execute("");
		// new Thread() {
		// public void run() {
		// lstProduct = loadData(SConfig.URL_BRAND_PRODUCTS);
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// refreshUI();
		// }
		// });
		// };
		// }.start();
		// GIFT
		lstGift = new ArrayList<ShoppieObject>();
		lstGiftAdapter = new BrandAdapter(this, lstGift);
		new AsyncTask<String, Integer, String>() {

			@Override
			protected String doInBackground(String... arg0) {
				lstGift = loadData(SConfig.URL_BRAND_GIFT);
				return null;
			}

			protected void onPostExecute(String result) {
				refreshUI();
			};
		}.execute("");
		// new Thread() {
		// public void run() {
		// lstGift = loadData(SConfig.URL_BRAND_GIFT);
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// refreshUI();
		// }
		// });
		// };
		// }.start();

		// REFRESH
		refreshUI();
	}

	private void refreshUI() {
		if (typeSelected == typeProduct) {
			lstProductAdapter = new BrandAdapter(this, lstProduct);
			((ListView) findViewById(R.id.lv_brand))
					.setAdapter(lstProductAdapter);
		} else {
			lstGiftAdapter = new BrandAdapter(this, lstGift);
			((ListView) findViewById(R.id.lv_brand)).setAdapter(lstGiftAdapter);
		}
		if (data instanceof Campaign) {
			Campaign cp = (Campaign) data;
			new AsyncTask<String, Integer, Bitmap>(){

				@Override
				protected Bitmap doInBackground(String... arg0) {
					return ((Campaign) data).getBitmap(getApplicationContext(), ((Campaign) data).linkImage);
				}
				protected void onPostExecute(Bitmap result) {
					if(result!=null){
						((ImageView) findViewById(R.id.iv_avatar)).setImageBitmap(result);
					}
				};
			}.execute("");
//			if (((Campaign) data).getBitmap(getApplicationContext(),
//					((Campaign) data).linkImage) != null) {
//				((ImageView) findViewById(R.id.iv_avatar)).setImageBitmap(cp
//						.getBitmap(getApplicationContext(), cp.linkImage));
//			}

		}
	}

	public void btnClicked(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			this.finish();
			break;
		case R.id.btn_sanpham:
			typeSelected = typeProduct;
			refreshUI();
			break;
		case R.id.btn_quatang:
			typeSelected = typeGift;
			refreshUI();
			break;
		default:
			break;
		}
	}

	private ArrayList<ShoppieObject> loadData(String typeLoad) {
		ArrayList<ShoppieObject> data = new ArrayList<ShoppieObject>();
		// load product
		try {
			ArrayList<NameValuePair> dataToSend = new ArrayList<NameValuePair>();
			dataToSend.add(new BasicNameValuePair(MERCH_ID, merchId));
			String xml = SUtilXml.getInstance().postXml(BrandActivity.this, SConfig.URL_SHOPPIE_HOME + typeLoad, dataToSend);
			// Log.e("xml",xml);
			if (xml.equals(null)) {
				showToast("Can not connect to Server");
				this.finish();
			}
			WiModelManager mng = new WiModelManager();
			mng.parse(xml);
			ArrayList<ShoppieObject> result = mng.getResultShoppieObject();
			Log.e("size " + typeLoad + ":", result.size() + "");
			for (ShoppieObject object : result) {
				data.add(object);
			}
			return data;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	Toast mToast;

	public void showToast(String text) {
		if (mToast == null)
			mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
		mToast.cancel();
		mToast.setText(text);
		mToast.show();
	}
}
